#!/bin/bash

# 洗护系统生产环境部署脚本

echo "🚀 开始部署洗护系统后端..."

# 设置变量
APP_NAME="laundry-care-backend"
APP_VERSION="1.0.0"
JAR_FILE="target/${APP_NAME}-${APP_VERSION}.jar"
PID_FILE="/var/run/${APP_NAME}.pid"
LOG_DIR="/var/log/laundry"
APP_DIR="/opt/laundry"

# 创建必要的目录
echo "📁 创建应用目录..."
sudo mkdir -p ${APP_DIR}
sudo mkdir -p ${LOG_DIR}
sudo mkdir -p /var/www/laundry/uploads

# 设置权限
sudo chown -R $USER:$USER ${APP_DIR}
sudo chown -R $USER:$USER ${LOG_DIR}
sudo chown -R $USER:$USER /var/www/laundry

# 停止现有服务
echo "⏹️ 停止现有服务..."
if [ -f ${PID_FILE} ]; then
    PID=$(cat ${PID_FILE})
    if ps -p $PID > /dev/null; then
        echo "停止进程 $PID"
        kill $PID
        sleep 5
        if ps -p $PID > /dev/null; then
            echo "强制停止进程 $PID"
            kill -9 $PID
        fi
    fi
    rm -f ${PID_FILE}
fi

# 构建应用
echo "🔨 构建应用..."
mvn clean package -DskipTests -Pprod

if [ ! -f ${JAR_FILE} ]; then
    echo "❌ 构建失败，JAR文件不存在: ${JAR_FILE}"
    exit 1
fi

# 备份旧版本
if [ -f ${APP_DIR}/${APP_NAME}.jar ]; then
    echo "📦 备份旧版本..."
    mv ${APP_DIR}/${APP_NAME}.jar ${APP_DIR}/${APP_NAME}.jar.backup.$(date +%Y%m%d_%H%M%S)
fi

# 复制新版本
echo "📋 复制新版本..."
cp ${JAR_FILE} ${APP_DIR}/${APP_NAME}.jar

# 创建systemd服务文件
echo "⚙️ 创建systemd服务..."
sudo tee /etc/systemd/system/${APP_NAME}.service > /dev/null <<EOF
[Unit]
Description=Laundry Care Backend Service
After=network.target mysql.service

[Service]
Type=simple
User=$USER
WorkingDirectory=${APP_DIR}
ExecStart=/usr/bin/java -jar -Dspring.profiles.active=prod ${APP_DIR}/${APP_NAME}.jar
ExecStop=/bin/kill -15 \$MAINPID
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=${APP_NAME}

[Install]
WantedBy=multi-user.target
EOF

# 重新加载systemd
sudo systemctl daemon-reload

# 启用服务
sudo systemctl enable ${APP_NAME}

# 启动服务
echo "🚀 启动服务..."
sudo systemctl start ${APP_NAME}

# 检查服务状态
sleep 10
if sudo systemctl is-active --quiet ${APP_NAME}; then
    echo "✅ 服务启动成功!"
    echo "📊 服务状态:"
    sudo systemctl status ${APP_NAME} --no-pager
else
    echo "❌ 服务启动失败!"
    echo "📋 查看日志:"
    sudo journalctl -u ${APP_NAME} --no-pager -n 20
    exit 1
fi

# 配置nginx反向代理
echo "🌐 配置Nginx..."
sudo tee /etc/nginx/sites-available/laundry-care > /dev/null <<EOF
server {
    listen 80;
    server_name your-domain.com;

    # API代理
    location /api/ {
        proxy_pass http://localhost:8080/api/;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_connect_timeout 30s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
    }

    # 静态文件
    location /uploads/ {
        alias /var/www/laundry/uploads/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # 前端静态文件
    location / {
        root /var/www/laundry/frontend;
        try_files \$uri \$uri/ /index.html;
        expires 1d;
        add_header Cache-Control "public";
    }
}
EOF

# 启用nginx站点
sudo ln -sf /etc/nginx/sites-available/laundry-care /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

echo "🎉 部署完成!"
echo "📍 应用地址: http://your-domain.com"
echo "📊 监控命令:"
echo "  - 查看服务状态: sudo systemctl status ${APP_NAME}"
echo "  - 查看日志: sudo journalctl -u ${APP_NAME} -f"
echo "  - 重启服务: sudo systemctl restart ${APP_NAME}"
echo "  - 停止服务: sudo systemctl stop ${APP_NAME}"
